package cn.hello2018.sdk.file;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.DecimalFormat;

/**
 * @author jeymingwu
 * @date 2019/5/9 10:28
 */
public class FileUtil {

    private static final long SIZE_B = 1024;
    private static final long SIZE_K = 1048576;
    private static final long SIZE_M = 1073741824;
    private static Logger logger = LoggerFactory.getLogger(FileUtil.class);

    /**
     * 获取单个文件大小
     *
     * @param file 文件
     * @return 文件大小
     * @throws IOException
     */
    public static Long getFileSize(File file) throws IOException {
        long size = 0;
        if (file.exists()) {
            FileInputStream fis = new FileInputStream(file);
            size = fis.available();
        } else {
            logger.error("文件不存在");
        }
        return size;
    }

    /**
     * 获取整个文件夹里文件的大小
     *
     * @param dir 文件夹
     * @return 所有文件大小
     * @throws IOException
     */
    public static Long getDirSize(File dir) throws IOException {
        long size = 0;
        File[] files = dir.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                size += getFileSize(file);
            } else {
                size += file.length();
            }
        }
        return size;
    }

    /**
     * 文件大小单位显示转换 - 与文件较为适合的单位
     *
     * @param size 文件大小字节数
     * @return 文件大小
     */
    public static String formatFileSize(Long size) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSize = "";
        if (size < SIZE_B) {
            fileSize = df.format((double) size) + "B";
        } else if (size < SIZE_K) {
            fileSize = df.format((double) size / SIZE_B) + "K";
        } else if (size < SIZE_M) {
            fileSize = df.format((double) size / SIZE_K) + "M";
        } else {
            fileSize = df.format((double) size / SIZE_M) + "G";
        }
        return fileSize;
    }

    /**
     * 获取文件夹下文件的个数
     *
     * @param dir
     * @return
     */
    public static long getDirNumber(File dir) {
        long number = new Long(0);
        File[] files = dir.listFiles();
        number = files.length;
        for (File file : files) {
            if (file.isDirectory()) {
                number += getDirNumber(file);
                --number;
            }
        }
        return number;
    }
}
